package ran.service;

import cn.hutool.core.lang.UUID;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ran.constants.JwtCacheConstants;
import ran.constants.RedisCacheConstants;
import ran.entity.LoginUser;
import ran.redis.service.RedisService;
import ran.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-10-09
 * Time: 15:42
 */
@Service
@Slf4j
public class TokenService {
    @Autowired
    private RedisService redisService;
    // 签发token
    public String createToken(long userId, String secret, Integer identity,String nickName, String headImage) {
        // jwt加密, 登录时加密
        Map<String, Object> claims = new HashMap<>();

        String userKey = UUID.fastUUID().toString(); // 随机出来的 key--UUID

        claims.put(JwtCacheConstants.LOGIN_USER_ID,userId);
        claims.put(JwtCacheConstants.LOGIN_USER_KEY,userKey);

        // 计算token
        String token = JwtUtils.createToken(claims, secret);


        String tokenKey = getTokenKey(userKey); // Redis中的key=固定前缀+jwt中的key
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);

        // redis 存储敏感信息, 用identity 表明用户的身份, key 前缀: login_token+UUID, val是identity类, 设置过期时间
        redisService.setCacheObject(tokenKey,loginUser ,RedisCacheConstants.EXP, TimeUnit.MINUTES);

        // 返回token
        return token;
    }
    // 拼装 TokenKey
    private String getTokenKey(String userKey) {
        return RedisCacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

    // 1.登录成功,调用tokenService, 生成token, 发送给客户端
    // 2.后续所有请求,先要通过token来身份认证
    // 3.用户使用中,适时延长jwt过期时间
    // 延长token有效期, 在拦截器中延长
    public void extendExpire(Claims claims) {
        String userKey = getUserKey(claims);
        if (userKey == null) {
            return;
        }
        String tokenKey = getTokenKey(userKey); // 获取Redis中token的key
        // 获取剩余的时间 redisService.expireTime()
        // 刷新有效期时间
        if (redisService.getExpireTime(tokenKey) < RedisCacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, RedisCacheConstants.EXP, TimeUnit.MINUTES);
        }
    }

    // 解析token, 返回userId
    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims)); // 获取jwt中的 userId
    }

    // 解析token, 返回 UserKey
    public String getUserKey(Claims claims) {
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims); // 获取jwt中的key
    }

    // 解析token, 返回 UserKey
    private String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims); // 获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); // 解析token
            if (claims == null) {
                log.error("token为解析为空, token:{}", token);
                return null;
            }
        }catch (Exception e) {
            log.error("token解析错误, token:{}, e:", token,e);
            return null;
        }
        return claims;
    }

    // 取出Redis中的LoginUser,并返回
    public LoginUser getLoginUser(String userKey) {
        if (userKey == null) {
            return null;
        }
        log.info("获取登录用户的userKey:{}",userKey);
        String tokenKey = getTokenKey(userKey); // 获取Redis中token的key
        return redisService.getCacheObject(tokenKey, LoginUser.class);
    }

    public boolean deleteLoginUser(String userKey) {
        if (userKey == null) {
            return false;
        }
        String tokenKey = getTokenKey(userKey); // 获取Redis中token的key
        return redisService.deleteObject(tokenKey);
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey); // 获取Redis中token的key
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey,loginUser);
    }
}
